const { date } = require('@hapi/joi');
const db = require('../db/index.js');

//导入bcript模块
const bcrypt = require('bcryptjs');
// 路由处理函数
// 向外暴露登录处理函数
exports.login = async (req, res) => {
  const user = req.body;
  // 查询用户
  const sql = 'SELECT * FROM User WHERE phone = ?';
  db.query(sql, user.phone, (err, results) => {
    if (err) return res.send({
      code: 1,
      message: err.message
    })
    if (!user) return res.status(404).json({ code: 1, message: "用户不存在" });
    // 验证密码
    const isValid = bcrypt.compare(user.password, results[0].password);
    if (!isValid) return res.status(401).json({ code: 1, message: "密码错误" });
    res.json({ code: 0, message: "登录成功", data: { id: results[0].id, name: results[0].name,phone: results[0].phone,avatar: results[0].avater } });
  })


}
// 向外暴露注册处理函数
exports.register = async (req, res) => {
  const user = req.body;

  // 检查手机号是否已存在
  const sql = 'select * from user where phone=?'
  db.query(sql, user.phone, (err, results) => {
    if (err) return res.send({
      code: 1,
      message: err.message
    })
    if (results.length !== 0) return res.send({
      code: 1,
      message: '手机号已存在'
    })
  })
  // 加密密码
  const hashedPassword = await bcript.hash(user.password, 10);

  // 插入数据库
  const result = ' INSERT INTO User (name, phone, password, gender) VALUES (?, ?, ?, ?)'
  db.query(result, [user.name, user.phone, hashedPassword, user.gender], (err, results) => {
    if (err) return res.send({
      code: 1,
      message: err.message
    })
    if (results.affectedRows !== 1) return res.send({
      code: 1,
      message: '注册失败'
    })
    res.send({
      code: 0,
      message: '注册成功'
    })
  })
}

//获取个人信息详情页函数
exports.getinfo = async (req, res) => {
  try {
    const userId = req.query.id; 
    // 查询数据库（排除 password 字段）
    const sql = 'select * from user where id=?'
    db.query(sql, userId, (err, results) => {
      if (err) return res.send({
        code: 1,
        message: err.message
      })
      if (results.length !== 1) return res.send({
        code: 1,
        message: '查询失败'
      })
      res.json({ code: 1, data: results[0] });
    })

  } catch (error) {
    res.status(500).json({ code: 500, message: "服务器内部错误" });
  }
}

//向外暴露 修改个人信息处理
exports.update = async (req, res) => {
  const user = req.body;
  const sql = 'update user set name=?, phone=?, gender=?,email=?,avatar=? where id=?';
  db.query(sql, [user.name, user.phone, user.gender,user.email,user.avatar,user.id], (err, results) => {
    if (err) return res.send({
      code: 1,
      message: err.message
    })
    if (results.affectedRows !== 1) return res.send({
      code: 1,
      message: '修改失败'
    })
    res.send({
      code: 0,
      message: '修改成功'
    })
  })
}